<?php
/**
 * Модель ленты файлов
 *
 * @package default
 * @author Alexander Sibiryakov
 **/
$this->useClass('AggregatedModel_Feed_ReaderItems');

class AggregatedModel_Feed_ReaderFiles extends AggregatedModel_Feed_ReaderItems implements AggregatedModel_Feed_FeedInterface
{
	var $type_descr = array(
		"pdf"=>"Документ Acrobat",
		"rar"=>"Архив RAR",
		"psd"=>"Документ Photoshop",
		"yml"=>"Документ YML",
		"mdl"=>"Документ MDL",
		);


	/**
	 * Вернет массив с кол-вом элементов по каждому типу файлов
	 *
	 * @return void
	 * @author Alexander Sibiryakov
	 **/
	public function getFileTypes() {
		return $this->types;
	}

	public function getFilesCount ()
	{
		return $this->files_count;
	} // end of method getFilesCount

	protected function prepare_where_query( $tag, $tdis, $community_oid, $filter_by_day=NULL, $user_oid=NULL, $filter_by_doctype=NULL )
	{
		$where = parent::prepare_where_query(
			$this->tag,
			$this->tdis_enum,
			$this->community_oid,
			$this->filter_by_day,
			$this->user_oid,
			$this->filter_by_doctype
		);

		// --- types --- {{{

		$types = $this->types;
		$db = $this->rh->ctx->db;
		// обернем в кавычки
		foreach ($types as $k=>$_t) {
			$q_types[$k] = $db->quote($_t);
		}

		if (!empty($types)) {
			$ws[] = "fstorage.ext IN (".implode(',', $q_types).")";
		}

		if ($where_types = implode (' AND ', $ws)) {
			$where = $where ? "$where AND $where_types" : "WHERE $where_types";
		}
		// --- types --- }}}

		return $where;
	}

	protected function fetch_posts( $q, $page_number, $struct_type )
	{
		// извлекает посты по where-части запроса и номеру страницы

		$where = $this->prepare_where_query(
			$this->tag,
			$this->tdis_enum,
			$this->community_oid,
			$this->filter_by_day,
			$this->user_oid,
			$this->filter_by_doctype
		);

		// извлекает посты по where-части запроса и номеру страницы
		$limit = ' limit '.($page_number-1) * $this->page_citems.','.$this->page_citems;
		if ($this->order_by=='name') $order_by = "ORDER BY fname DESC";
		else $order_by = '';

		$prefix = $this->rh->ctx->db->db_prefix;
		$sql ="
		SELECT -- выбираем объекты из allfeed
			fstorage.real_fname AS fname,
			fstorage.file_size AS size,
			{$prefix}objects.ctime AS ctime, -- спросить тут иванова
			fstorage.ext,
			allfeed.posted_by_id,
			fstorage.oid AS oid,
			allfeed.oid AS item_oid,
			allfeed.posted_by_id AS useroid
		FROM {$prefix}objects
			INNER JOIN store_class_allfeed AS allfeed ON ({$prefix}objects.oid = allfeed.oid AND allfeed.is_deleted = 0)
			INNER JOIN store_class_filestorage AS fstorage ON fstorage.oid = allfeed.file_oid

		$where
		$limit
		";

		$ors = new DBStoreResult($this->rh->ctx->store, $this->rh->ctx->store->query( $sql ));

		if (!$ors) { echo "there is no available feed for you"; return false; }

		$sql_possible_types = "
		SELECT
			ext,
			count(ext) AS cnt
		FROM store_class_filestorage fstorage
			INNER JOIN store_class_allfeed allfeed ON fstorage.oid = allfeed.file_oid AND allfeed.is_deleted = 0
		$where
		GROUP BY ext
		ORDER BY ext
		";

		$possible_types = $this->rh->ctx->db->query($sql_possible_types);
		///$files_count = $possible_types['0']['all_cnt'];
		$files_count = 0;
		// скопируем массив типов и в цикле будем каждому типу добавлять кол-во файлов этого типа
		foreach($possible_types as $key=>$arry) {
			$ext = $arry['ext'];
			$descr = isset($this->type_descr[ $ext ])?$this->type_descr[ $ext ]:'нет описания';
			$_t = array(
				'descr' => $descr,
				'ext' => $ext,
				'count' => $arry['cnt'],
				'selected' => in_array($ext, $types)?1:0
				);

			$files_count += $_t['count'];
			$_types[ $ext ] = $_t;
		}

		while ($obj = $ors->next()) {

			$row = $ors->rs->current();
			// найдем автора
			$c['user']['oid']['==']=$obj->data['posted_by_id'];
			$result = $this->rh->ctx->store->find( $c );
			$user = $result->next();
			unset($result, $c);

			$item = array(
				"fname"=>$row['fname'],
				"ext"=>$row['ext'],
				"user"=>$user->data,
				"size"=>$row['size'],
				"oid"=>$row['oid'],
				"useroid"=>$row['useroid'],
				"item_oid"=>$row['item_oid'],
				"type"=>"ffile",
				"date"=>RL_CyrDate::newFromStr("%Y-%m-%d %H:%i:%s", $row['ctime']),
				);

			$items[] = $item;

		}

		$this->files_count = $files_count;
		$this->types = $_types;

		return $items;
	}

} // END class


